package Email.auto.checker;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Listener for the "open in browser" button.
 * 
 * @author Andre Duarte - duarte.andre00@gmail.com
 * @author Marcio Almeida - marcio.bastos.almeida@gmail.com
 * 
 */
public class ClickButtonOpenBrowser implements ActionListener {

	/**
	 * Reference to the notification class.
	 */
	private Notification notification;
	/**
	 * Variable to save the network address for the email server.
	 */
	private String emailServerAddress;

	/**
	 * ClickButtonOpenBrowser constructor.
	 * 
	 * @param nT
	 *            - Notification object
	 */
	public ClickButtonOpenBrowser(final Notification nT) {
		if (nT == null) {
			throw new IllegalArgumentException();
		}
		notification = nT;
		emailServerAddress = null;
	}

	/**
	 * Gets the network address for the email server.
	 * 
	 * @param mail
	 *            - the email address
	 * @return the network address for the email server
	 */
	public final String getNetworkAddress(final String mail) {

		if (mail == null) {
			return null;
		}

		String domain;
		String[] part;

		part = mail.split("@");
		domain = part[1];

		if (domain.equals("isec.pt")) {
			emailServerAddress = "http://webmail.isec.pt";
		}

		if (domain.equals("gmail.com")) {
			emailServerAddress = "http://mail.google.com";
		}

		if (domain.equals("hotmail.com")) {
			emailServerAddress = "http://hotmail.com";
		}

		return emailServerAddress;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String aux = notification.getStringMail();
		emailServerAddress = getNetworkAddress(aux);
		if (emailServerAddress == null) {
			throw new IllegalArgumentException();
		}

		if (!java.awt.Desktop.isDesktopSupported()) {

			System.err.println("Desktop is not supported (fatal)");
			System.exit(1);
		}

		java.awt.Desktop desktop = java.awt.Desktop.getDesktop();

		if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {

			System.err
					.println("Desktop doesn't support the browse action (fatal)");
			System.exit(1);
		}

		try {
			java.net.URI uri = new java.net.URI(emailServerAddress);
			desktop.browse(uri);
		} catch (Exception e1) {
			System.err.println(e1.getMessage());
		} finally {
			notification.dispose();
		}

	}

}
